<template>
  <div>
      <h1>添加</h1>
      <a-form >
        <a-form-item label="标题" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
          <a-input v-model="title"/>
        </a-form-item>

        <a-form-item label="缩略图" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
          <input type="file" @change="handleThumb">
        </a-form-item>

        <a-form-item label="内容" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
          <div ref="editor" style="text-align:left"></div>
        </a-form-item>
      </a-form>
      <div style="text-align: center;" @click="addPost">
        <a-button type="">
          添加文章
        </a-button>
      </div>
  </div>
</template>

<script>
import * as api from '@/api'
import E from 'wangeditor'

export default {
  data () {
    return {
      title: '',
      editorContent: '',
      thumb: null
    }
  },
  mounted () {
    this.$nextTick().then(() => {
      var editor = new E(this.$refs.editor)
      editor.customConfig.onchange = (html) => {
        this.editorContent = html
      }
      editor.create()
    })
  },
  methods: {
    handleThumb (e) {
      let currentDOM = e.target
      let file = currentDOM.files[0]
      let fr = new FileReader()
      fr.readAsDataURL(file)
      fr.onload = () => {
        this.thumb = fr.result
      }
    },
    addPost () {
      if (this.editorContent && this.title) {
        // let user = JSON.parse(localStorage.getItem('user'))
        api.addPost({
          title: this.title,
          content: this.editorContent,
          thumb: this.thumb
        }).then(r => {
          if (r.code === 200) {
            this.$message.info(r.message)
            this.title = ''
            this.editorContent = ''
          }
        })
      }
    }
  }
}
</script>

<style>

</style>
